package com.xyx.yfy_site_msg.system.controller;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xyx.yfy_site_msg.system.entity.*;
import com.xyx.yfy_site_msg.system.service.YfyCustomerService;
import com.xyx.yfy_site_msg.system.service.YfySiteService;
import com.xyx.yfy_site_msg.system.service.YfySystemService;
import com.xyx.yfy_site_msg.system.utils.Constast;
import com.xyx.yfy_site_msg.system.utils.DataGridView;
import com.xyx.yfy_site_msg.system.utils.ResultObj;
import com.xyx.yfy_site_msg.system.utils.WebUtils;
import com.xyx.yfy_site_msg.system.vo.YfyCustomerVo;
import com.xyx.yfy_site_msg.system.vo.YfySiteVo;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;

import java.io.Serializable;
import java.util.*;

/**
 * <p>
 * 前端控制器
 * </p>
 *
 * @author xyx
 * @since 2020-11-17
 */
@RestController
@RequestMapping("/customer")
public class YfyCustomerController {

    @Autowired
    private YfyCustomerService customerService;

    @Autowired
    private YfySystemService systemService;

    @Autowired
    private YfySiteService siteService;

    /*
     * 查询所有客户数据返回json
     * */
    @RequestMapping("loadAllCustomer")
    public DataGridView loadAllCustomer(YfyCustomerVo customerVo) {
        IPage<YfyCustomer> page = new Page<>(customerVo.getPage(), customerVo.getLimit());
        QueryWrapper<YfyCustomer> queryWrapper = new QueryWrapper<>();
        YfyUser user = (YfyUser) WebUtils.getSession().getAttribute("user");
        if (user.getUsertype() == Constast.USER_TYPE) {
            queryWrapper.select("id", "customer", "person", "post", "telephone", "address", "city", "sitenum");
            queryWrapper.like(StringUtils.isNotBlank(customerVo.getCustomer()), "customer", customerVo.getCustomer());
            queryWrapper.like(StringUtils.isNotBlank(customerVo.getTelephone()), "telephone", customerVo.getTelephone());
            queryWrapper.orderByDesc("id");
            this.customerService.page(page, queryWrapper);
        } else {
            queryWrapper.like(StringUtils.isNotBlank(customerVo.getCustomer()), "customer", customerVo.getCustomer());
            queryWrapper.like(StringUtils.isNotBlank(customerVo.getTelephone()), "telephone", customerVo.getTelephone());
            queryWrapper.like(StringUtils.isNotBlank(customerVo.getFounder()), "founder", customerVo.getFounder());
            queryWrapper.like(StringUtils.isNotBlank(customerVo.getCustid()), "custid", customerVo.getCustid());
            queryWrapper.ge(customerVo.getStartTime() != null, "createtime", customerVo.getStartTime());
            queryWrapper.le(customerVo.getEndTime() != null, "createtime", customerVo.getEndTime());
            queryWrapper.ge(customerVo.getStartUpdateTime() != null, "updatetime", customerVo.getStartUpdateTime());
            queryWrapper.le(customerVo.getEndUpdateTime() != null, "updatetime", customerVo.getEndUpdateTime());
            queryWrapper.orderByDesc("id");
            try {
                this.customerService.page(page, queryWrapper);
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return new DataGridView(page.getTotal(), page.getRecords());
    }

    /*
     * 添加客户数据
     * */
    @RequestMapping("addCustomer")
    public ResultObj addCustomer(YfyCustomerVo customerVo) {
        try {
            YfyUser user = (YfyUser) WebUtils.getSession().getAttribute("user");
            String deploymentid = customerVo.getDeployment();
            String deployment = this.systemService.loadDeploymentById(deploymentid);
            customerVo.setDeployment(deployment);
            String sourceofcustomerid = customerVo.getSourceofcustomer();
            String sourceofcustomer = this.systemService.loadSourceOfCustomerById(sourceofcustomerid);
            customerVo.setSourceofcustomer(sourceofcustomer);
            if (sourceofcustomer == null) {
                sourceofcustomer = "受理";
                customerVo.setSourceofcustomer(sourceofcustomer);
            }
            String addressid = customerVo.getAddress();
            String address = this.systemService.loadAddressById(addressid);
            if (address == null) {
                address = "暂无";
                customerVo.setAddress(address);
            }
            customerVo.setAddress(address);
            String cityid = customerVo.getCity();
            String city = this.systemService.loadAddressById(cityid);
            customerVo.setCity(city);
            customerVo.setFounder(user.getUsername());
            customerVo.setCreatetime(new Date());
            YfySystem customerType = this.systemService.getById(customerVo.getCustomertype());
            if (null != customerType) {
                customerVo.setCustomertype(customerType.getDeployment());
            } else {
                customerVo.setCustomertype("测试客户类别");
            }
            YfySystem product = this.systemService.getById(customerVo.getProduct());
            if (null != product) {
                customerVo.setProduct(product.getDeployment());
            } else {
                customerVo.setProduct("测试产品");
            }
            customerVo.setSite("测试站点");
            if (customerType != null) {
                String customerTypes = customerType.getDeployment();
                YfySiteVo siteVo = new YfySiteVo();
                if (null != customerTypes && customerTypes.equals(Constast.CUSTOMER_TYPES)) {
                    siteVo.setCustid(customerVo.getCustid());
                    siteVo.setCustomer(customerVo.getCustomer());
                    siteVo.setSitename(customerVo.getSite());
                    siteVo.setName(customerVo.getPerson());
                    siteVo.setTelephone(customerVo.getTelephone());
                    siteVo.setHelp(customerVo.getHelp());
                    siteVo.setPost(customerVo.getPost());
                    siteVo.setProblem(customerVo.getProblem());
                    siteVo.setDeployment(deployment);
                    siteVo.setS95a1v(customerVo.getC95a1());
                    siteVo.setS95a2v(customerVo.getC95a2());
                    siteVo.setS9511v(customerVo.getC9511());
                    siteVo.setS9512v(customerVo.getC9512());
                    siteVo.setS9001v(customerVo.getC9001());
                    siteVo.setSourceofcustomer(customerVo.getSourceofcustomer());
                    siteVo.setCenterdbv(customerVo.getCenterdb());
                    siteVo.setOildbv(customerVo.getC9511db());
                    siteVo.setCloudv(customerVo.getCloud());
                    siteVo.setFrogv(customerVo.getFrog());
                    String p15 = customerVo.getP15();
                    String p32 = customerVo.getP32();
                    String p58 = customerVo.getP58();
                    if (p15 != null || p32 != null || p58 != null) {
                        siteVo.setWisdom("15寸【" + p15 + "】/32寸【" + p32 + "】/5.8寸【" + p58 + "】");
                    }
                    siteVo.setSelfservice(customerVo.getSelfservice());
                    siteVo.setOilengine(customerVo.getOilengine());
                    siteVo.setMessage(customerVo.getMessage());
                    siteVo.setSubmitter(user.getUsername());
                    siteVo.setSubmissiontime(new Date());
                }
                this.siteService.save(siteVo);
            }
            this.customerService.save(customerVo);
            return ResultObj.ADD_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.ADD_ERROR2;
        }
    }

    /*
     * 删除客户数据
     * */
    @RequestMapping("deleteCustomer")
    public ResultObj deleteCustomer(YfyCustomerVo customerVo) {
        try {
            //通过客户id查询yfy_customer表查到客户名customer；然后通过customer删除yfy_site表中对应所有的行
            Integer id = customerVo.getId();
            String customerName = this.customerService.loadCustomerNameById(id);
            this.siteService.removeSiteByCustomerName(customerName);
            this.customerService.removeById(id);
            return ResultObj.DELETE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.DELETE_ERROR;
        }
    }

    /*
     * 批量删除客户数据
     * */
    @RequestMapping("batchDeleteCustomer")
    public ResultObj batchDeleteCustomer(YfyCustomerVo customerVo) {
        try {
            Collection<Serializable> idList = new ArrayList<>();
            for (Integer id : customerVo.getIds()) {
                String customerName = this.customerService.loadCustomerNameById(id);
                this.siteService.removeSiteByCustomerName(customerName);
                idList.add(id);
            }
            this.customerService.removeByIds(idList);
            return ResultObj.DELETE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.DELETE_ERROR;
        }
    }


    /*
     * 更新客户数据
     * */
    @RequestMapping("updateCustomer")
    public ResultObj updateCustomer(YfyCustomerVo customerVo) {
        try {
            YfyUser user = (YfyUser) WebUtils.getSession().getAttribute("user");
            customerVo.setUpdatebody(user.getUsername());
            customerVo.setUpdatetime(new Date());
            String deploymentid = customerVo.getDeployment();
            String deployment = this.systemService.loadDeploymentById(deploymentid);
            customerVo.setDeployment(deployment);
            String sourceofcustomerid = customerVo.getSourceofcustomer();
            String sourceofcustomer = this.systemService.loadSourceOfCustomerById(sourceofcustomerid);
            customerVo.setSourceofcustomer(sourceofcustomer);
            String addressid = customerVo.getAddress();
            String address = this.systemService.loadAddressById(addressid);
            customerVo.setAddress(address);
            String cityid = customerVo.getCity();
            String city = this.systemService.loadAddressById(cityid);
            customerVo.setCity(city);
            YfySystem customerType = this.systemService.getById(customerVo.getCustomertype());
            customerVo.setCustomertype(customerType.getDeployment());
            YfySystem product = this.systemService.getById(customerVo.getProduct());
            customerVo.setProduct(product.getDeployment());
            String customerTypes = customerType.getDeployment();
            YfySiteVo siteVo = new YfySiteVo();
            if (customerTypes.equals(Constast.CUSTOMER_TYPES)) {
                this.customerService.updateById(customerVo);
                siteVo.setCustid(customerVo.getCustid());
                siteVo.setCustomer(customerVo.getCustomer());
                siteVo.setSitename(customerVo.getSite());
                siteVo.setName(customerVo.getPerson());
                siteVo.setTelephone(customerVo.getTelephone());
                siteVo.setHelp(customerVo.getHelp());
                siteVo.setPost(customerVo.getPost());
                siteVo.setProblem(customerVo.getProblem());
                siteVo.setDeployment(deployment);
                siteVo.setS95a1v(customerVo.getC95a1());
                siteVo.setS95a2v(customerVo.getC95a2());
                siteVo.setS9511v(customerVo.getC9511());
                siteVo.setS9512v(customerVo.getC9512());
                siteVo.setS9001v(customerVo.getC9001());
                siteVo.setSourceofcustomer(customerVo.getSourceofcustomer());
                siteVo.setCenterdbv(customerVo.getCenterdb());
                siteVo.setOildbv(customerVo.getC9511db());
                siteVo.setCloudv(customerVo.getCloud());
                siteVo.setFrogv(customerVo.getFrog());
                String p15 = customerVo.getP15();
                String p32 = customerVo.getP32();
                String p58 = customerVo.getP58();
                if (p15 != null || p32 != null || p58 != null) {
                    siteVo.setWisdom("15寸【" + p15 + "】/32寸【" + p32 + "】/5.8寸【" + p58 + "】");
                }
                siteVo.setSelfservice(customerVo.getSelfservice());
                siteVo.setOilengine(customerVo.getOilengine());
                siteVo.setMessage(customerVo.getMessage());
                siteVo.setUpdatebody(user.getUsername());
                siteVo.setUpdatetime(new Date());

                Integer id = customerVo.getId();
                String time = this.customerService.loadCustomerTimeById(id);

                QueryWrapper<YfySite> queryWrapper = new QueryWrapper<>();
                queryWrapper.eq("S_SubmissionTime", time);
                this.siteService.update(siteVo, queryWrapper);
                return ResultObj.UPDATE_SUCCESS;
            }
            this.customerService.updateById(customerVo);
            return ResultObj.UPDATE_SUCCESS;
        } catch (Exception e) {
            e.printStackTrace();
            return ResultObj.UPDATE_ERROR;
        }
    }

    /*
     * 加载所有客户下拉菜单
     * */
    @RequestMapping("loadAllCustomerSelect")
    public DataGridView loadAllCustomerSelect() {
        QueryWrapper<YfyCustomer> customerQueryWrapper = new QueryWrapper<>();
        customerQueryWrapper.orderByDesc("createtime");
        List<YfyCustomer> list = this.customerService.list(customerQueryWrapper);
        return new DataGridView(list);
    }

    /*
     * 加载所有部署方式
     * */
    @RequestMapping("loadAllDeploymentSelect")
    public DataGridView loadAllDeploymentSelect() {
        QueryWrapper<YfySystem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", Constast.DEPLOYMENT_TYPE);
        List<YfySystem> list = this.systemService.list(queryWrapper);
        return new DataGridView(list);
    }

    /*
     * 加载所有客户来源类型
     * */
    @RequestMapping("loadAllSourceOfCustomerSelect")
    public DataGridView loadAllSourceOfCustomerSelect() {
        QueryWrapper<YfySystem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", Constast.SOURCE_OF_CUSTOMER);
        List<YfySystem> list = this.systemService.list(queryWrapper);
        return new DataGridView(list);
    }

    /*
     * 加载所有的省份至下拉菜单
     * */
    @RequestMapping("loadAllProvinceSelect")
    public DataGridView loadAllProvinceSelect() {
        QueryWrapper<YfySystem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", Constast.PROVINCE_TYPE);
        List<YfySystem> list = this.systemService.list(queryWrapper);
        return new DataGridView(list);
    }

    /**
     * 加载所有客户类型下拉菜单
     *
     * @return
     */
    @RequestMapping("loadAllCustomerType")
    public DataGridView loadAllCustomerType() {
        QueryWrapper<YfySystem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", Constast.CUSTOMER_TYPE);
        List<YfySystem> list = this.systemService.list(queryWrapper);
        return new DataGridView(list);
    }

    /**
     * 加载所有产品类型下拉菜单
     *
     * @return
     */
    @RequestMapping("loadAllProductType")
    public DataGridView loadAllProductType() {
        QueryWrapper<YfySystem> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("type", Constast.PRODUCT_TYPE);
        List<YfySystem> list = this.systemService.list(queryWrapper);
        return new DataGridView(list);
    }

    /*
     * 客户地区数据分析json
     * */
    @RequestMapping("loadAllCustomerOfProvince")
    public Map<String, Object> loadAllCustomerOfProvince() {
        List<YfyDataEntity> list = this.customerService.loadAllCustomerOfProvince();
        Map<String, Object> map = new HashMap<>();
        List<String> names = new ArrayList<>();
        List<Double> values = new ArrayList<>();
        for (YfyDataEntity baseEntity : list) {
            names.add(baseEntity.getName());
            values.add(baseEntity.getValue());
        }
        map.put("name", names);
        map.put("value", values);
        return map;
    }
    /*
     * 客户地区数据分析json【饼状图】
     * */
//    @RequestMapping("loadAllCustomerOfProvince")
//    public List<YfyDataEntity> loadAllCustomerOfProvince() {
//        return this.customerService.loadAllCustomerOfProvince();
//    }

    /*
     * 根据省份查询相对应的城市下拉框
     * */
    @RequestMapping("loadCityByAddressId")
    public DataGridView loadCityByAddressId(Integer addressid) {
        List<YfySystem> list = this.systemService.loadCityByAddressId(addressid);
        return new DataGridView(list);
    }

    /**
     * 客户地区分布数量关系数量由多到少
     *
     * @return
     */
    @RequestMapping("loadAllAddressOfCount")
    public DataGridView loadAllAddressOfCount() {
        List<YfyDataEntity> list = this.customerService.loadAllAddressOfCount();
        return new DataGridView(list);
    }

    /*
     * 查询客户档案提交数据
     * */
    @RequestMapping("loadCreate")
    @ResponseBody
    public Map<String, Object> loadCreate(String month) {
        List<YfyDataEntity> list = this.customerService.loadCreate(month);
        Map<String, Object> map = new HashMap<>();
        List<String> names = new ArrayList<>();
        List<Double> values = new ArrayList<>();
        for (YfyDataEntity baseEntity : list) {
            names.add(baseEntity.getName());
            values.add(baseEntity.getValue());
        }
        map.put("name", names);
        map.put("value", values);
        return map;
    }

    /*
     * 查询客户档案更新数据
     * */
    @RequestMapping("loadUpdate")
    @ResponseBody
    public Map<String, Object> loadUpdate(String month) {
        List<YfyDataEntity> list = this.customerService.loadUpdate(month);
        HashMap<String, Object> map = new HashMap<>();
        List<String> names = new ArrayList<>();
        List<Double> values = new ArrayList<>();
        for (YfyDataEntity dataEntity : list) {
            names.add(dataEntity.getName());
            values.add(dataEntity.getValue());
        }
        map.put("name", names);
        map.put("value", values);
        return map;
    }

    /*
     * 客户地区数据分析json
     * */
    @RequestMapping("loadOther")
    public Map<String, Object> loadOther() {
        List<YfyOther> list = this.customerService.loadOther();
        HashMap<String, Object> map = new HashMap<>();
        List<String> address1 = new ArrayList<>();
        List<Double> customer1 = new ArrayList<>();
        List<Double> site1 = new ArrayList<>();
        List<Double> sum1 = new ArrayList<>();
        for (YfyOther other : list) {
            address1.add(other.getAddress());
            customer1.add(other.getCustomer());
            site1.add(other.getSite());
            sum1.add(other.getSum());
        }
        map.put("address", address1);
        map.put("customer", customer1);
        map.put("site", site1);
        map.put("sum", sum1);
        return map;
    }
}
